package com.ruoyi.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisDistributedLock {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private static final long DEFAULT_EXPIRE_TIME = 10;
    private static final long DEFAULT_WAIT_TIME = 5;
    private static final long RETRY_INTERVAL = 100;

    private static final String RELEASE_SCRIPT =
            "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                    "   return redis.call('del', KEYS[1]) " +
                    "else " +
                    "   return 0 " +
                    "end";

    /**
            * 获取分布式锁
     * @param lockKey 锁的Key
     * @return 锁的唯一标识，获取失败返回null
     */
    public String acquireLock(String lockKey) {
        return acquireLock(lockKey, DEFAULT_EXPIRE_TIME, DEFAULT_WAIT_TIME);
    }

    /**
     * 获取分布式锁
     * @param lockKey 锁的Key
     * @param expireTime 锁的过期时间（秒）
     * @param waitTime 获取锁的等待时间（秒）
     * @return 锁的唯一标识，获取失败返回null
     */
    public String acquireLock(String lockKey, long expireTime, long waitTime) {
        long endTime = System.currentTimeMillis() + waitTime * 1000;
        String lockValue = UUID.randomUUID().toString();
        while (System.currentTimeMillis() < endTime) {
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, expireTime, TimeUnit.SECONDS);

            if (Boolean.TRUE.equals(lock)){
                return lockValue;
            }
            try {
                Thread.sleep(100);
            }catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return null;
            }
        }
        return null;
    }

    /**
     * 释放分布式锁
     * @param lockKey 锁的Key
     * @param lockValue 锁的唯一标识
     * @return 是否成功释放锁
     */
    public boolean releaseLock(String lockKey, String lockValue) {
        if (lockValue == null)
            return false;

        DefaultRedisScript<Long> script = new DefaultRedisScript<>(RELEASE_SCRIPT, Long.class);

        Long result = (Long) redisTemplate.execute(script, Collections.singletonList(lockKey), lockValue);
        return result != null && result > 0L;
    }

}
